import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

import { asyncRoutes } from '@/router/index'
import orderlist  from '@/views/order/orderlist'
import Layout from '@/layout'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
import {creatrouter } from  '@/utils/index'
const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      // if(  store.getters.routes.length>0  ){  // 如果 有角色 那么百分百 需要添加路由
      //   router.addRoutes( store.getters.routes ) 
      //   next({  ...to , replace:true })
      // }
      console.log( "当前路由信息",router.getRoutes());
      // console.log(router);
//  如果访问的路径中 没有在路由信息中那么要去添加一下路由
          console.log("router.getters.roles.length",store.getters.roles);
      if(store.getters.roles.length ==0 ){
        // 发现没有就重新发送请求 去得到路由表 
        await store.dispatch('user/getInfo')
      //  await store.dispatch('user/setRouter')
        // console.log( "正在加载路由现在的路由",  router.getRoutes());
         next({  ...to , replace:true })
      }
      if (hasGetUserInfo) {
        next()
      } else {
          // get user info
          await store.dispatch('user/resetToken')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
